﻿using System.Text.RegularExpressions;
using MelonLoader;
using MelonLoader.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace SultanModLoader
{
    public class AssetsTool
    {
        /// <summary>
        /// 将路径转为系统标准格式
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string UnifyPathSeparator(string path)
        {
            return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar) ;
        }


        /// <summary>
        /// 生成10种长度的空白字符
        /// </summary>
        public static readonly List<string> SPACE_LEVELS = Enumerable.Range(0, 10).Select(i => new string(' ', 4 * i)).ToList();
        public static void LevelMsg(Object info, int level = 0, ConsoleColor color = ConsoleColor.White)
        {
            
            level = Math.Max(level, 0);
            level = Math.Min(level, SPACE_LEVELS.Count - 1);
            MelonLogger.Msg(color, $"{SPACE_LEVELS[level]}{info?.ToString()}");
        }


        // 递归复制目录的方法
        public static void CopyDirectory(string sourceDir, string destinationDir)
        {
            // 获取源目录信息
            var dir = new DirectoryInfo(sourceDir);

            // 检查源目录是否存在
            if (!dir.Exists)
                throw new DirectoryNotFoundException($"源目录不存在: {dir.FullName}");

            // 如果目标目录不存在，则创建
            Directory.CreateDirectory(destinationDir);

            // 复制所有文件
            foreach (FileInfo file in dir.GetFiles())
            {
                string targetFilePath = Path.Combine(destinationDir, file.Name);
                file.CopyTo(targetFilePath, false); // false表示不覆盖已存在的文件
            }

            // 递归复制子目录
            foreach (DirectoryInfo subDir in dir.GetDirectories())
            {
                string newDestinationDir = Path.Combine(destinationDir, subDir.Name);
                CopyDirectory(subDir.FullName, newDestinationDir);
            }
        }
    

        // 清洗json
        public static string CleanJson(string json)
        {
            // 先处理字符串内容，保护字符串内的所有内容不被修改
            string pattern = @"(""(?:\\""|[^""])*"")|(/\*.*?\*/|//[^\r\n]*(?=[\r\n]|$))";

            // 使用正则替换，只处理不在字符串内的注释
            string cleaned = Regex.Replace(json, pattern, match =>
            {
                // 如果是字符串内容，保留原样
                if (match.Groups[1].Success)
                {
                    return match.Groups[1].Value;
                }
                // 否则是注释，替换为空
                return string.Empty;
            }, RegexOptions.Singleline);

            // 移除尾随逗号（在}或]前的逗号）
            cleaned = Regex.Replace(cleaned, @",(\s*[}\]])", "$1");

            return cleaned;
        }

        /// <summary>
        /// 从文件解析Json对象
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static JObject ParseJsonFile(string filePath)
        {
            if (!File.Exists(filePath)) return null;
            string jsonContent = File.ReadAllText(filePath);
            string cleanJson = CleanJson(jsonContent);

            try
            {
                return JObject.Parse(cleanJson);
            }
            catch (JsonException ex)
            {
                MelonLogger.Error($"解析JSON文件 {filePath} 时出错: {ex.Message}");
                return new JObject();
            }
        }
    }
}
